package net.alche.ext.dbUtil.connect.dbs;
import net.alche.ext.dbUtil.connect.DBConnect;
import java.sql.Connection;
import net.alche.ext.dbUtil.connect.def.DbConfig;
import java.sql.DriverManager;
import java.sql.ResultSet;

//
//
// /** 数据库连接Mysql实现
//
// @author:姚礼武
// @time: [2018年04月11 11:12:24 ]
// @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
//
public class DBConnectMysql implements DBConnect {
    String driverName = "com.mysql.cj.jdbc.Driver";
    String dbName = "";
    Connection dbConn = null;
    DbConfig config;

  public DBConnectMysql(DbConfig config) {
    this.config = config;
    dbName = config.DB_NAME;
  }

  public Connection getConn() {
    if (dbConn == null) {
      String dbURL = "jdbc:mysql://" + config.DB_IP + ":" + config.DB_PORT_MYSQL + "/" + dbName+ "?allowMultiQueries=true";
      try {
        Class.forName(driverName);
        Connection dbConn = DriverManager.getConnection(dbURL, config.DB_UID, config.DB_PWD);
        this.dbConn = dbConn;
        return dbConn;
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    else {
      return dbConn;
    }
    return null;
  }

  public void close() {
    if (dbConn != null) {
      try {
        dbConn.close();
      }
      catch (Exception e) {}
    }
  }

  @Override
  public int getDbType() {
    return 1;
  }

  @Override
  public String getUserName() {
    return config.DB_UID;
  }

  @Override
  public String getTableRemark(String tableName) {
    String sql = "select table_comment from information_schema.tables where table_name  = '" + tableName + "'";
    try {
      ResultSet rs = getConn().createStatement().executeQuery(sql);
      if (rs.next()) {
        String remark = rs.getString("table_comment");
        rs.close();
        return remark;
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }
}